package Helpers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


public class FileHelper {
	
	private static String directoryPath = "/sdcard/Beneficios/";
	private static long timeToDelete = 432000000;
	private FileHelper(){
		
	}
	
	private static void saveUrlAsPngFile2(String urlPath,String fileName) throws IOException{
		
		//String fileName = getNameOfFileFromUrl(urlPath);
		URL url = new URL (urlPath);
		InputStream input = url.openStream();
		try {
		    OutputStream output = new FileOutputStream (directoryPath+fileName);
		    try {
		    	int bufferSize = 1024;
		        byte[] buffer = new byte[bufferSize];
		        int bytesRead = 0;
		        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
		            output.write(buffer, 0, buffer.length);
		        }
		    }catch(Exception e){
		    	File fileToDelete = new File(directoryPath+fileName);
		    	fileToDelete.delete();
		    } 
		    finally {
		        output.close();
		    }
		}catch(Exception e){
	    	File fileToDelete = new File(directoryPath+fileName);
	    	fileToDelete.delete();
	    } 
		finally {
		    input.close();
		}
		
	}
	
	 public static void saveUrlAsPngFile( String imagePath, String imageName) {
		 try {
		 File f = new File(directoryPath+ imageName);
		 imagePath = imagePath.replaceAll(" ", "%20");
		 imagePath = imagePath.replace("|", "%7C");
		 HttpGet httpRequest = new HttpGet(imagePath);
		 HttpClient httpclient = new DefaultHttpClient();
		 HttpResponse response = (HttpResponse) httpclient
		 .execute(httpRequest);
		 HttpEntity entity = response.getEntity();
		 BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
		 entity);
		 InputStream is = bufferedHttpEntity.getContent();

		 Bitmap bmp = BitmapFactory.decodeStream(is);

		 FileOutputStream out = new FileOutputStream(f);
		 bmp.compress(Bitmap.CompressFormat.PNG, 99, out);
		 out.close();

		 } catch (MalformedURLException e) {
		 // TODO Auto-generated catch block
		 e.printStackTrace();
		 } catch (IOException e) {
		 // TODO Auto-generated catch block
		 e.printStackTrace();
		 }
		 catch (Exception e) {
			 // TODO Auto-generated catch block
			 e.printStackTrace();
			 }
		 }

	
	
	private static String getNameOfFileFromUrl(String url){
		String[] splittedUrl = url.split("/");
		int size = splittedUrl.length;
		String imageCategory = splittedUrl[size-3];
		String imageId = splittedUrl[size-2];
		String fileNameWithNumbers = splittedUrl[size-1];
		String[] splittedUrlSecond = fileNameWithNumbers.split("\\?");
		String fileName = splittedUrlSecond[0];
		if (splittedUrlSecond.length > 1){
			fileName += splittedUrlSecond[1];
		}
		String fileNameWithId = imageCategory + imageId + fileName;
		return fileNameWithId;

	}
	
	private static boolean fileExist(String filePath){
		
		File directory = new File(directoryPath);
		boolean a = directory.exists();
		if(!a){
			directory.mkdirs();
		}
		File file = new File(directoryPath+filePath);
		boolean b = file.exists();
		return b;
	}
	
	public static Bitmap getImageBitMap(String image,String mapName) throws IOException{
		
		if(mapName == ""){
			String imageName = FileHelper.getNameOfFileFromUrl(image);
			if( !FileHelper.fileExist(imageName)){
				FileHelper.saveUrlAsPngFile(image,imageName);
			
			}
			String pathForFile= directoryPath+imageName;
			Bitmap bitmap = BitmapFactory.decodeFile(pathForFile);
			return bitmap;
		}else{
			return FileHelper.getLocationMapBitMap(mapName,image);
		}
		
		
	}

	private static Bitmap getLocationMapBitMap(String mapName, String image) throws IOException{
		//if( !FileHelper.fileExist(mapName)){
		//	FileHelper.saveUrlAsPngFile(image,mapName);
		
		//}
		image = image.replaceAll(" ", "%20");
		image = image.replace("|", "%7C");
		 HttpGet httpRequest = new HttpGet(image);
		 HttpClient httpclient = new DefaultHttpClient();
		 HttpResponse response = (HttpResponse) httpclient
		 .execute(httpRequest);
		 HttpEntity entity = response.getEntity();
		 BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
		 entity);
		 InputStream is = bufferedHttpEntity.getContent();

		 Bitmap bmp = BitmapFactory.decodeStream(is);
		return bmp;
		
		
	}


	public static String getNameOfMapFromUrl(String url) {
		String[] splittedUrl = url.split("/");
		int size = splittedUrl.length;
		String fileNameWithNumbers = splittedUrl[size-1];
		String[] splittedUrlSecond = fileNameWithNumbers.split("\\?");
		String latLonWithParameters = splittedUrlSecond[splittedUrlSecond.length -1];
		String[] splittedUrlThird = latLonWithParameters.split("\\|");
		String latLong = splittedUrlThird[splittedUrlThird.length-1];
		String fileName = "map" + latLong + ".png";
		return fileName;
	}


	public static void deleteOldFiles() {
		File directory = new File(directoryPath);
		boolean a = directory.exists();
		if(a){
			String[] files = directory.list();
			for(int i = 0; i < files.length; i++){
				String filePath = files[i];
				File file = new File(directoryPath+filePath);
				if(FileHelper.isdeletedNeeded(file)){
					file.delete();
				}
			}
		}
	}

	private static boolean isdeletedNeeded(File file) {
		Date currentdDate = new Date();
		Date lastModifcationDate = new Date( file.lastModified());
		if( lastModifcationDate.getTime() + timeToDelete < currentdDate.getTime()){
			return true;
		}
		
		return false;
	}
	
}
